const symId = Symbol("mqtt");
export default class MqttClient {
  constructor(id) {
    if (id !== symId) {
      throw new Error("请使用 createClient 方法创建mqtt实例");
    }
  }
  static client;
  // #mqttUrl = "wss://srs.hiwords.net/mqtt";
  #mqttUrl = "wss://mqtt.top237.top/mqtt";
  #mqttOptions = {
    clean: true,
    connectTimeout: 4000,
    // 认证信息
    clientId: `sgb_${+new Date()}`,
    username: `sgb_${+new Date()}`,
    password: "emqx_test",
  };

  static createClient() {
    const client = new MqttClient(symId);
    return client.createConnection();
  }

  createConnection() {
    return new Promise((resolve, reject) => {
      if (MqttClient.client) {
        resolve(MqttClient.client);
        return;
      }
      const client = window.mqtt.connect(this.#mqttUrl, this.#mqttOptions);
      if (client.on) {
        client.on("connect", () => {
          MqttClient.client = client;
          resolve(client);
        });

        client.on("error", (error) => {
          reject(error);
        });
      }
    });
  }

  static destory() {
    if (MqttClient.client.connected) {
      try {
        MqttClient.client.end(false, () => {
          console.log("Successfully disconnected!");
          MqttClient.client = null;
        });
      } catch (error) {
        console.log("Disconnect failed", error.toString());
      }
    }
  }
}
